# -*- encoding:utf-8 -*-
from demo import app
from demo.utils.funs import *
from . import render_template, route
from demo.models.role import Role
from demo.models.menu import Menu
from flask import g, request, redirect, url_for, flash

@route('/role/list')
@login_required
@check_access
def role_list():

    page = get_params('p', default=1, type=int)
    size = 30
    condition = {}
    role_obj = Role()
    for k in role_obj.cols:
        v = request.args.get(k)
        if v:
            condition[k] = [v, '=']

    data, page = role_obj.find_pageble(condition, page, size)
    return render_template('/role/list.html', list=data, page=page, req=request.args)



@route('/role/edit', methods=['GET', 'POST'])
@login_required
@check_access
def role_edit():

    id = get_params('id', default=None)

    role_obj = Role()
    menus = Menu().find_all()
    if request.method == 'GET':
        # to new
        if not id:
            return render_template('/role/edit.html', role={}, req=request.args, menus=menus)

        # to edit
        data = role_obj.find(id)
        return render_template('/role/edit.html', role=data, req=request.args, menus=menus)

    # save
    try:
        name = get_params('name', required='缺少角色参数')
        menu_ids = get_params('menu_ids', required='缺少菜单JSON参数', is_list=True)
    except Exception as e:
        return show_error(str(e))

    menu_ids = ','.join(menu_ids)

    data = {"name": name, "menu_ids": menu_ids}
    if id:
        res = role_obj.save(data, id)
        if res:
            flash('保存成功')
    else:
        res = role_obj.save(data)
        if not res:
            return show_error('用户已存在')
        else:
            flash('保存成功')

    return redirect(request.headers.get('referer'))



@route('/role/del', methods=['POST'])
@login_required
@check_access
def role_del():

    id = get_params('id', required='缺少必要参数')

    role_obj = Role()
    if role_obj.delete(id):
        flash('删除成功')
    else:
        return show_error('删除失败，请联系管理员')
    return redirect(request.headers.get('referer'))

